package com.zsc.edu.gateway.modules.attachment.controller;

import com.zsc.edu.gateway.exception.StorageException;
import com.zsc.edu.gateway.framework.storage.exception.StorageFileNotFoundException;
import com.zsc.edu.gateway.modules.attachment.entity.Attachment;
import com.zsc.edu.gateway.modules.attachment.service.AttachmentService;
import com.zsc.edu.gateway.modules.operationLog.entity.OperationLogAnnotation;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件Controller
 *
 * @author harry_yao
 */
@AllArgsConstructor
@RestController
@RequestMapping("api/rest/attachment")
public class AttachmentController {

    private final AttachmentService service;

    /**
     * 上传附件
     *
     * @param type 附件功能类型
     * @param file 文件
     * @return 附件信息
     */
    @PostMapping()
    @OperationLogAnnotation(content = "'附件上传'", operationType = "新建")
    public Attachment upload(
        @RequestParam(required = false, defaultValue = "其他") Attachment.Type type,
        @RequestParam("file") MultipartFile file
    ) {
        try {
            if (type == null) {
                type = Attachment.Type.其他;
            }
            return service.store(type, file);
        } catch (IOException e) {
            throw new StorageException("文件上传出错");
        }
    }

    /**
     * 下载附件
     *
     * @param id 附件ID
     * @return 附件文件内容
     */
    @GetMapping("{id}")
    public ResponseEntity<Resource> download(
        @PathVariable("id") String id
    ) {
        Attachment.Wrapper wrapper = service.loadAsWrapper(id);
        if (wrapper.attachment.fileName != null) {
            ContentDisposition contentDisposition = ContentDisposition.builder("attachment").filename(wrapper.attachment.fileName, StandardCharsets.UTF_8).build();
            return ResponseEntity.ok().
                header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString()).
                header(HttpHeaders.CONTENT_TYPE, wrapper.attachment.mimeType).
                body(wrapper.resource);
        }
        return ResponseEntity.ok(wrapper.resource);
    }

    /**
     * 预览附件
     *
     * @param id 附件ID
     * @return 附件文件内容（直接预览）
     */
    @GetMapping("/preview/{id}")
    public ResponseEntity<?> preview(
            @PathVariable("id") String id
    ) {
        try {
            Attachment.Wrapper wrapper = service.loadAsWrapper(id);
            String mimeType = wrapper.attachment.mimeType;

            // 如果是图片或 PDF，直接返回文件流
            if (mimeType.startsWith("image/") || mimeType.equals("application/pdf")) {
                ContentDisposition contentDisposition = ContentDisposition.builder("inline")
                        .filename(wrapper.attachment.fileName, StandardCharsets.UTF_8)
                        .build();

                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString())
                        .header(HttpHeaders.CONTENT_TYPE, mimeType)
                        .body(wrapper.resource);
            } else {
                // 如果是文本文件，直接返回文本内容
                String content = new String(wrapper.resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
                return ResponseEntity.ok(content);
            }
        } catch (StorageFileNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件读取失败");
        }
    }

    /**
     * 根据附件ID获取附件信息
     * */
    @GetMapping("find/{id}")
    public Attachment getAttachmentInfo(@PathVariable("id") String id) {
        return service.getById(id);
    }


    /**
     * 批量上传附件
     */
    @PostMapping("multipartFile")
    @OperationLogAnnotation(content = "'附件批量上传'", operationType = "新建")
    public List<Attachment> uploadMultipleFiles(
            @RequestParam(defaultValue = "其他") Attachment.Type type,
            @RequestParam("files") List<MultipartFile> files
    ) throws IOException {
        List<Attachment> attachments = new ArrayList<>();
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                attachments.add(service.stores(type, file));
            }
        }
        return attachments;
    }

    /**
     * 根据附件ID删除附件信息
     */
    @DeleteMapping("delete/{id}")
    @OperationLogAnnotation(content = "'附件'", operationType = "删除")
    public Boolean delete(@PathVariable("id") String id) {
        return service.delete(id);
    }

}
